<?php

namespace app\controller;

use app\BaseController;
use app\common\LxApi;
use FFMpeg\Coordinate\TimeCode;
use FFMpeg\FFMpeg;
use Lexiangla\Openapi\VodApi;
use think\Exception;
use think\facade\Db;
use Qcloud\Cos\Client as CosClient;

class Lexiangla extends BaseController
{
    use \app\common\Tools;

    public $Lxapi;
    public $staff_id = '1e04fd5c55794b0e902bebcba61d5e7d';
    public $base_path = "/mnt/d/资源文件夹/";

    // 初始化
    protected function initialize()
    {

        //73df2040f65f11ea9d2f52540005f435
        $appkey = "73df2040f65f11ea9d2f52540005f435";
        $appsecret = "xtzLmnzOsIoG6tqc3WkniPBlQGAAdpCMRfo4JhtU";
        $this->Lxapi = new LxApi($appkey, $appsecret);
        $this->Lxapi->forStaff($this->staff_id);
    }

    public function test1()
    {
        $file = 'D:\资源整理合集\王木木\绵阳市南山中学实验学校政治61王木木\1155_人教版政治意识的能动作用 南山实验郑娜.MP4';
        $fie_info = pathinfo($file);
        dump($fie_info);
        dump(explode("\\", $fie_info['filename']));
    }

    public function updateDocFile1()
    {

        $dir = 'D:\资源整理合集';
        $file_list = $this->getDir($dir, true);

        foreach ($file_list as $key => $value) {
            $file_id = explode('_', $value['filename']);
            $file_id = is_array($file_id) ? $file_id[0] : $file_id;
            if (strstr($file_id, '\\')) {
                $file_id = explode('\\', $file_id);
                $file_id = array_pop($file_id);
            }

            $file_id = (int)$file_id;
            $data = [
                'file_path' => $value['filepath'],
                'file_size' => $value['size'],
                'file_type' => $value['extension'],
            ];

            // dump([ $value, $file_id ]);
            $re = DB::table('lexiang')
                ->where([ 'file_id' => $file_id ])
                ->update($data);
            dump([ $value, $re, $key, $file_id ]);
        }
    }

    public function updateDocFile2()
    {
        $response_db = DB::table('lexiang')
            ->whereNull('file_is_upload')
            ->whereNotNull('file_path')
            ->where('file_size < 108986745')
            ->order('file_size asc')
            ->select();
        $i = 0;
        $n = 0;
        $number = [ $i, $n ];
        foreach ($response_db as $key => $item) {
            $this->upload($item, $number);
        }
    }

    public function upOnes()
    {
        $number = [ 0, 1 ];
        $this->upload([
            'uid'       => 'b83deef439d211eb978722b950db24b8',
            'title'     => '高三语文模拟试题——陈冬',
            'file_path' => 'D:\资源整理合集\叶诗齐\电教馆征集绵中优秀教育资源汇集\1语文18\1_高三语文模拟试题绵阳中学陈冬.docx',
            'file_type' => 'docx'

        ], $number);
    }

    public function upload($item, &$number = [])
    {
        $video_types = [ 'avi', 'f4v', 'flv', 'mp3', 'mp4', 'mpg', 'qlv', 'rmvb', 'wmv' ];

        if (!in_array($item['file_type'], $video_types)) {
            $options = [
                'name'         => $item['title'] . '.' . $item['file_type'],
                'downloadable' => 1 // 是否可下载
            ];
            $response_att = $this->Lxapi->uploadAttachment($this->staff_id, $item['file_path'], $options);
            if (isset($response_att['data']['id'])) {
                $response = $this->Lxapi->patchDocument($this->staff_id, $item['uid'], [ 'attachments' => [ $response_att['data']['id'] ] ]);
                if (!isset($res['errors'])) {
                    DB::table('lexiang')
                        ->where([ 'uid' => $item['uid'] ])
                        ->update([ 'file_is_upload' => 1 ]);
                    $number[0]++;
                    dump([ '(●ˇ∀ˇ●) | 上传成功：', $number[0], $item['uid'], $item['title'], ]);
                } else {
                    DB::table('lexiang')
                        ->where([ 'uid' => $item['uid'] ])
                        ->update([ 'file_is_upload' => 0 ]);
                    $number[1]++;
                    dump([ '::>_<:: | 上传失败：', $number[1], $item['uid'], $item['title'], $response ]);
                }
            } else {
                $number[1]++;
                DB::table('lexiang')
                    ->where([ 'uid' => $item['uid'] ])
                    ->update([ 'file_is_upload' => 0 ]);
                dump([ '::>_<:: | 附件上传失败：', $number[1], $item['uid'], $item['title'], $response_att ]);
            }
        }

    }


    public function checkFileOnline()
    {
        $response_db = DB::table('lexiang')
            ->whereNotNull('check_file_is_upload')
            ->order('file_id asc')
            ->select();
        $i = 0;

        foreach ($response_db as $key => $value) {
            $response = $this->Lxapi->get('docs/' . $value['uid']);

            if (isset($response['data']['relationships']['attachments'])) {
                if (count($response['data']['relationships']['attachments']['data']) >= 1) {
                    $i++;
                    DB::table('lexiang')
                        ->where([ 'uid' => $value['uid'] ])
                        ->update([ 'check_file_is_upload' => 1 ]);
                    dump('上传成功：' . $i . '个资源！');
                }
            } else {
                dump('上传失败：' . $value['uid'] . '资源！');

            }
        }
    }

    public function updateAll()
    {
        $video_files = Db::table('lexiang')
//            ->where('uid', '5b3e6d4e39d411eba03272f061aad91f')
            ->where([ 'is_update' => 0 ])
            ->order('file_size asc')
            ->select();
        $i = 0;
        $j = 0;
        foreach ($video_files as $video_file) {

            $this->updateOne($video_file, $i);
            if ($j = 5) {
                sleep(2);
                $j = 0;
            }

        }
    }

    public function updateOne($item = [], &$i = 0)
    {
//        $item['uid'] = 'e72c483c39d211eba9799ec2a822dab9';
//        $item['file_type'] = 'mp4';
        //获取单个文档
        $options = [];
        $response = $this->Lxapi->get('docs/' . $item['uid']);

        if (isset($response['data'])) {
            dump($response['data']['attributes']['name']);

            //替换标题问号
            $title = str_replace('?', ' ', $response['data']['attributes']['name']);
            if ($title !== $item['title']) {
                dump('替换标题:');
                $options['title'] = $title;
                $options['target_type'] = 'document';
            }

            //清楚文档中的视频附件
            $video_types = [ 'avi', 'f4v', 'flv', 'mp3', 'mp4', 'mpg', 'qlv', 'rmvb', 'wmv' ];
            if (in_array($item['file_type'], $video_types)) {
                dump('清楚文档中的视频附件:');
                $options['target_type'] = 'document';
                $options['attachments'] = [];
            }
            //替换署名、摘要内的问号和正文内的附件名称
            foreach ($response['included'] as $value) {
                if ($value['type'] == 'document') {
                    $options['target_type'] = 'document';
                    $options['summary'] = str_replace('?', ' ', $value['attributes']['summary']);
                    $options['signature'] = str_replace('?', ' ', $value['attributes']['signature']);
                    $content = explode('附件名称', $value['attributes']['content'])[0];
                    $options['content'] = $content . '</div>';
                }
            }


            if (count($options) > 0) {
                dump('开始执行:');
                $i++;

                $patchDoc = $this->Lxapi->patchDoc($this->staff_id, $item['uid'], $options);
                if (isset($patchDoc['included'])) {
                    Db::table('lexiang')->where([ 'uid' => $item['uid'] ])->update([ 'is_update' => 1 ]);
                    dump([ $patchDoc['included'][2], $i ]);

                } else {
                    dump('更新失败！:');
                    Db::table('lexiang')->where([ 'uid' => $item['uid'] ])->update([ 'is_update' => 2 ]);
                }

            } else {
                dump('不需要更新！:');
                Db::table('lexiang')->where([ 'uid' => $item['uid'] ])->update([ 'is_update' => 3 ]);
            }

        } else {
            dump('获取不到文档！:');
            Db::table('lexiang')->where([ 'uid' => $item['uid'] ])->update([ 'is_update' => 4 ]);
            dump($response);
        }

    }

    public function video($video_path)
    {
        //one
        $signature = $this->Lxapi->post('videos/upload-signature');
        $signature = isset($signature['signature']) ? $signature['signature'] : false;
        if ($signature) {
            //two
            $cover_img_path = $this->getVideoImage($video_path);

            $vodApi = new VodApi($signature, $video_path, $cover_img_path);
            return $vodApi->uploadVideo();
        }
    }

    public function getVideoImage($VideoPath, $Seconds = 1)
    {
        try {
            $iamge_name = pathinfo($VideoPath)['basename'];
            $ffmpeg = FFMpeg::create([
                'ffmpeg.binaries'  => '/usr/bin/ffmpeg',
                'ffprobe.binaries' => '/usr/bin/ffprobe',
            ]);
            $video = $ffmpeg->open($VideoPath);
            $frame = $video->frame(TimeCode::fromSeconds($Seconds)); //获取第几帧
            $iamge_path = runtime_path() . $iamge_name . '.jpg';
            $frame->save($iamge_path); //获取图片
            return $iamge_path;
        } catch (\Exception $th) {

            return runtime_path() . 'cover_img.png';
        }
    }

    public function bigFileUpload()
    {
        $this->video('/mnt/d/big.mp4');
    }

    /**
     * 将分类存储到数据库
     */
    public function getCategoryToDb($pid = '')
    {
        $params['target_type'] = 'doc';
        if ($pid !== '') {
            $params['parent_id'] = $pid;
        }

        $response = $this->Lxapi->get('categories', $params);
        foreach ($response['data'] as $key => $value) {
            $data = [
                'uid'            => $value['id'],
                'pid'            => $pid,
                'name'           => $value['attributes']['name'],
                'children_count' => $value['meta']['children_count']
            ];
            Db::table('category')->insert($data);
            if ($value['meta']['children_count'] > 0) {
                $this->getCategoryToDb($value['id']);
            }
        }

        dump($response);
    }

    /**
     * 获取分类的顶级父ID
     */
    public function getCategoryPid($cid = '')
    {
        if ($cid == '') {
            return '';
        }
        $data = Db::table('category')->select()->toArray();
        foreach ($data as $k => $v) {
            $arr[$v['uid']] = $v['pid'];
        }
        $id = $cid;
        while ($arr[$id]) { //这个循环是个关键，也比较简单
            $id = $arr[$id];
        }
        return $id;
    }

    public function CheckCategoryPid($cid)
    {
        $pid = $this->getCategoryPid($cid);
        return in_array($pid, [ 'f0f135dc263911ebaf1e9ae2842cc77a', 'adb60b14272c11eb9766464f829a8367' ]);
    }

    /**
     * 获取资源列表标题名称和ID
     */
    public function getListTest()
    {
        $response_db = Db::table('lexiangla')
            // ->where(['created_at' => '2020-12-01'])
            // ->where('is_sync is null')
            // ->limit(10, 4)
            ->order('id asc')
            ->select();

        foreach ($response_db as $key => $values) {

            $response = $this->Lxapi->get('docs/' . $values['uid']);

            $attachment_ids = [];

            if (isset($response['data']['relationships']['attachments'])) {
                foreach ($response['data']['relationships']['attachments']['data'] as $key => $value) {
                    dump($value['id']);
                    $attachment_ids[] = $value['id'];
                }
                $data = [
                    'title'             => $values['title'],
                    'doc_id'            => $values['uid'],
                    'attachment_ids'    => json_encode($attachment_ids),
                    'attachment_number' => count($attachment_ids)
                ];
                Db::table('online')->insert($data);
                dump([ $key, $data ]);
            }
        }
    }

    /**
     * 清理附件名称前面的路径
     */
    public function files()
    {
        $response_db = DB::table('files')->order('id asc')->select();
        foreach ($response_db as $key => $value) {
            $name = explode('/', $value['name']);
            if (is_array($name)) {
                $name = array_pop($name);
                DB::table('files')->where([ 'id' => $key ])->update([ 'name' => $name ]);
            }
        }
    }

    /**
     * 清理附件名称前面的路径
     */
    public function attachment()
    {
        $response_db = DB::table('attachment')->order('id asc')->select();
        foreach ($response_db as $key => $value) {
            $name = explode('/', $value['name']);
            if (is_array($name)) {
                $name = array_pop($name);
                DB::table('attachment')->where([ 'id' => $key ])->update([ 'name' => $name ]);
            }
        }
    }

    public function classes()
    {
        $response = $this->Lxapi->get('classes/96cfadb02d4411ebbb3c52540005f435');
        dump($response);

    }

    public function search()
    {
        $keyword = '人教版?绘画?第六课?色彩的表现与材料的选择——色彩画初试?油画综合材料——塑型膏的使用——魏楠';
        return $this->Lxapi->get('search?type=doc&keyword=' . $keyword . '&page=1&per_page=10');
    }


    public function searchDoc()
    {
        $response = $this->Lxapi->get('docs/03407286338511ebba520a9922f37a7c');
        //                                   bef74aec370c11eb9ac4962b2cc8a1b6
        dump($response);
    }

    public function searchAttc()
    {
        $response = $this->Lxapi->get('attachments/a4151276371211eb8398aabbe7e89921');
        dump($response);
    }


    /**
     * 获取资源列表标题名称和ID
     */
    public function getList()
    {
        for ($i = 1; $i <= 387; $i++) {
            $response = $this->Lxapi->get('docs', [
                'filter'   => 'all',
                'page'     => $i,
                'per_page' => 100
            ]);
            $new_data = [];
            // dump($response);
            foreach ($response['data'] as $key => $value) {
                //获取列表数据
                $new_data[$key]['id'] = $value['id'];
                $new_data[$key]['name'] = $value['attributes']['name'];

                //判断并获取分类ID
                if ($value['relationships']['category']['data']['type'] == 'category') {
                    $new_data[$key]['category'] = $value['relationships']['category']['data']['id'];
                    if ($this->CheckCategoryPid($new_data[$key]['category'])) {
                        Db::table('lexiangla')->insert([
                            'uid'        => $value['id'],
                            'title'      => $value['attributes']['name'],
                            'created_at' => date("Y-m-d", strtotime($value['attributes']['created_at'])),
                        ]);
                    }
                }
            }
            dump($new_data);
            dump($response['meta']);
        }
    }

    public function test()
    {
        $str = '38人教版地理高二上必修3第2.1荒漠化的防治（绵阳南山中学实验学校杨舰）_20201118133945.pdf';
        $str2 = '人教版地理高二上必修3第2.1荒漠化的防治_20201118134006——杨舰';
        similar_text($str, $str2, $number);
        return floor($number);
    }

    public function tupload()
    {
        $response = $this->Lxapi->uploadAttachment($this->staff_id, '/mnt/f/小皮面板初始信息.txt', [
            'name'         => '小皮面板初始信息.txt',
            'downloadable' => 1 // 是否可下载
        ]);
        // dump($response);
        dump($response['data']['relationships']['attachments']);
    }

    public function syncOne($docs_id, array $attachments)
    {
        $res = $this->Lxapi->patchDocument($this->staff_id, $docs_id, [ 'attachments' => $attachments ]);
        return $this->Lxapi->get('docs/' . $docs_id);
    }

    public function syncAll($docs_id, array $attachments)
    {

        $response = $this->syncOne($docs_id, $attachments);
        if (isset($response['data']['relationships']['attachments'])) {
            return count($response['data']['relationships']['attachments']['data']) >= 1 ? true : false;
        }
        return false;
    }

    public function sync()
    {
        //return $this->syncAll('bef74aec370c11eb9ac4962b2cc8a1b6', ['a4151276371211eb8398aabbe7e89921']);
        $teacher_name = explode('—', '人民版历史高二上必修三专题三第二课新文化运动新文化运动——');
        dump($teacher_name);
        $teacher_name = array_pop($teacher_name);

        return count(explode($teacher_name, '1人民版历史，高一年级上册，专题五现代中国的外交【复习课】（四川省绵阳中学  蹇福）.ppt')) > 1;
    }

    public function updateDoc()
    {
        $response_lexiangla = Db::table('lexiangla')
            // ->where(['created_at' => '2020-12-01'])
            // ->where('is_sync is null')
            ->whereLike('title', "%人教版语文高一年级必修一梳理探究《优美的汉字》——王吉美%")
            // ->limit(23)
            ->order('id asc')
            ->select();
        $i = 0;
        $response_attachment = DB::table('attachment')
            ->where('uid is not null')
            ->select();
        foreach ($response_lexiangla as $key => $item) {
            // dump('explode1 ' . $item['title']);
            $teacher_name = explode('—', $item['title']);
            if (is_array($teacher_name)) {
                $teacher_name = array_pop($teacher_name);
            }

            $i++;
            //取资源ID并更新；
            $options = [];
            $array_similar = [];
            foreach ($response_attachment as $k => $val) {

                similar_text($val['name'], $item['title'], $number);
                $number = floor($number);
                // dump('explode2 :' . $teacher_name . '---------' . $val['name']);
                if ($teacher_name !== '') {
                    if ($number > 80 && count(explode($teacher_name, $val['name'])) > 1) {
                        $options['attachments'][] = $val['uid'];
                        dump($item['title'] . ' ===> ' . $val['name'] . "匹配度:" . $number . "%");
                        $array_similar[$k] = [
                            'similar' => $number,
                            'ids'     => $val['id'],
                        ];
                    }
                } else {
                    if ($number > 90) {
                        $options['attachments'][] = $val['uid'];
                        dump($item['title'] . ' ===> ' . $val['name'] . "匹配度:" . $number . "%");
                        $array_similar[$k] = [
                            'similar' => $number,
                            'ids'     => $val['id'],
                        ];
                    }
                }
            }
            if (empty($options)) {
                dump('未找到资源');
                continue;
            }

            $response = $this->syncAll($item['uid'], $options['attachments']);
            if ($response) {
                dump([ $i . '__更新资源:', $item['title'], $item['uid'], $options ]);

                dump([ $item['uid'], $options, $i ]);
                DB::table('lexiangla')->where([ 'uid' => $item['uid'] ])
                    ->update([
                        'is_sync'           => 1,
                        'similar'           => json_encode($array_similar),
                        'attachment_ids'    => json_encode($options['attachments']),
                        'attachment_number' => count($options['attachments'])
                    ]);
                dump('更新资源完成');
            } else {
                DB::table('lexiangla')->where([ 'uid' => $item['uid'] ])
                    ->update([ 'is_sync' => 0 ]);
            }
        }
    }

    public function getFilelist()
    {
        $base_path = "/mnt/d/资源文件夹/";
        $path_list = $this->getDir($base_path);
        dump($path_list);
    }


    public function db()
    {
        $response = Db::table('attachment')->where('id', 1)->select();
        dump($response);
    }


//    public function upload($name, $file_path)
//    {
//        $response = $this->Lxapi->uploadAttachment($this->staff_id, $file_path, [
//            'name'         => $name,
//            'downloadable' => 1 // 是否可下载
//        ]);
//        return $response;
//    }

    /**
     * 检查以上传文档附件数量
     */
    public function attachment_number()
    {
        foreach (Db::table('online')->select() as $key => $value) {
            $attachment_number = json_decode($value['attachment_ids'], true);
            if (!empty($attachment_number)) {
                dump($attachment_number);
                DB::table('online')->where([ 'id' => $key ])->update([ 'attachment_number' => count($attachment_number) ]);
            }
        }
    }

    /**
     *
     */
    public function attachment_name1()
    {
        foreach (Db::table('attachment')->where('id', 2846)->select() as $key => $value) {
            $path_array = explode('/', $value['local_path']);
            if (is_array($path_array)) {
                $name = array_pop($path_array);
                DB::table('attachment')->where([ 'id' => $key ])->update([ 'name' => $name ]);
                dump($name);
            }
        }
    }

    /**
     *
     */
    public function attachment_name()
    {
        foreach (Db::table('attachment')->select() as $key => $value) {
            $path_array = (int)mb_substr($value['name'], 0, 3);
            dump($path_array);
            //DB::table('attachment')->where(['id' => $key])->update(['name' => $name]);
        }
    }

    public function only_upload()
    {
        $base_path = "F:\资源整理合集\\";
        // $path_list =    $this->getDir($base_path);
        $path_list = DB::table('files')->order('size asc')->select();

        foreach ($path_list as $key => $value) {
            $path_parts = pathinfo($value['path']);
            $response_db = DB::table('attachment')->where([ 'name' => $path_parts['basename'] ])->find();
            if (!$response_db) {
                dump('开始上传：' . $path_parts['basename']);
                try {
                    $response = $this->upload($path_parts['basename'], $value['path']);

                    if (isset($response['data']) && count($response['data']) > 0) {

                        $data = [
                            'uid'        => $response['data']['id'],
                            'name'       => $path_parts['basename'],
                            'local_path' => $value['path'],
                            'is_upload'  => 1
                        ];
                        dump('上传完成存入数据库：' . $path_parts['basename']);
                        $response_db = DB::table('attachment')->insert($data);
                        if (!$response_db) {
                            break;
                        }
                    } else {
                        dump('上传失败' . $path_parts['basename']);
                    }
                    dump($data);
                } catch (\Throwable $th) {
                    $data = [

                        'name'       => $path_parts['basename'],
                        'local_path' => $value['path'],
                        'is_upload'  => 0
                    ];
                    dump('上传失败' . $path_parts['basename']);
                    $response_db = DB::table('attachment')->insert($data);
                }
            }
        }
    }

    public function path()
    {

        return $this->getDir(root_path() . 'config', true);
    }
}
